
"use strict";
/**
 *
 * @author wangchenzhao
 * @date 2018/11/20
 */
const Service = require('egg').Service;
const Json2csvParser = require('json2csv').Parser;
class template extends Service {

  constructor(param) {
    super(param);
    this.mysql = this.app.database.exam_mysql;
  }
  async export_csv(list, cnkeys) {
    const fields = [];
    let data = []
    list.forEach(element => {
      const value = {}
      for (const key in element) {
        if (element.hasOwnProperty(key)) {
          //const element = object[key];
          for (const cnkey in cnkeys) {
            if (cnkeys.hasOwnProperty(cnkey)) {
              //const element = cnkeys[cnkey];
              if (cnkey === key) {
                value[cnkeys[cnkey]] = (element[key] === '' || element[key] === null) ? '' : element[key]
              }
            }
          }

        }
      }
      data.push(value)
    });
    for (const key in list[0]) {
      if (list[0].hasOwnProperty(key)) {
        for (const cnkey in cnkeys) {
          if (cnkeys.hasOwnProperty(cnkey)) {
            if (cnkey === key) fields.push(cnkeys[cnkey])
          }
        }
      }
    }
    console.log(data);

    const json2csvParser = new Json2csvParser({ fields });
    let csv = json2csvParser.parse(data);

    data = [{ 'fields': data }]
    const a = ['fields'];
    const json2csvParser2 = new Json2csvParser({ a });
    let csv2 = json2csvParser2.parse(data);

    csv2 = Buffer.concat([new Buffer('\xEF\xBB\xBF', 'binary'), new Buffer(csv2)])
    return csv2;
  }
}


module.exports = template;

